const { postNewsData } = require('../../../api/home')
// pages/news/news.js
Page({
  data: {
    newslist: [],
    height: '',
    page: 0
  },
  onLoad() {
    // 监听窗口高度
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          height: res.windowHeight
        })
      },
    })
    this.fetchNewsData()
  },
  imageError(e){
    const id = e.currentTarget.dataset.item.id
    const item = this.data.newslist.find(item=>item.id == id)
    item.picUrl = '../../../img/no-data.png'
    this.setData({
      newslist:this.data.newslist
    })
  },
  //请求新闻数据
  async fetchNewsData() {
    try {
      wx.showLoading({
        title: '加载中'
      })
      const res = await postNewsData({
        page: this.data.page,
        num: 10
      })
      this.setData({
        newslist: [...this.data.newslist, ...res.newslist]
      })
    } catch (e) {
      wx.showToast({
        title: JSON.stringify(e),
      })
    } finally {
      wx.hideLoading()
    }
  },

  //下拉触底事件
  loadMore() {
    this.setData({
      page:++this.data.page
    })
    this.fetchNewsData()
  },

  //新闻点击事件
  newsTap(e) {
    let newsUrl = e.target.dataset.url
    wx.setStorageSync('newsUrl', newsUrl);
    wx.navigateTo({
      url: '../newsInfo/newsInfo',
    })
  },

  onReady() {

  },

  onShow() {

  },

  onHide() {

  },

  onUnload() {

  },

  onPullDownRefresh() {

  },

  onReachBottom() {

  },

  onShareAppMessage() {

  }
})